/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.server.error.model;

import javax.servlet.http.HttpServletRequest;
import offset.nodes.server.error.controller.ErrorAttribute;

/**
 * Used to have a common source for the error handling
 * in both struts and error page.
 *
 * The struts error handling has been added to avoid
 * the overview of the additional tomcat logs about
 * the exception in this case.
 * 
 * @author Walter L�tgenau
 */
public class ErrorHandler {
     public static final String PATTERN_SEPARATOR = "::";

    /**
     * Check for a wrapped logged exception.
     * If it cannot be found, create a general logged exception to log the problem.
     * 
     * @param request
     * @param exception
     * @return
     */
    public static LoggedException processException(HttpServletRequest request, Throwable exception) {
        LoggedException loggedException = getLoggedException(exception);
        if (loggedException == null)
            loggedException = new LoggedException(ExceptionId.GENERAL_SYSTEM_EXCEPTION, exception);
        ErrorAttribute error = new ErrorAttribute(loggedException);
        request.setAttribute(error.getId(), error);

        return loggedException;
    }

    /**
     * Check for a wrapped LoggedException
     * 
     * @param exception
     * @return
     */
    protected static LoggedException getLoggedException(Throwable exception) {
        do {
            if (exception instanceof LoggedException)
                return (LoggedException) exception;
            exception = exception.getCause();
        } while(exception != null);

        return null;
    }

    /**
     * Split error message, if it is structured by PATTERN_SEPARATOR
     * 
     * @param message
     * @param title
     * @return
     */
    public static String getMessage(String message, StringBuffer title) {
        if (message.indexOf(PATTERN_SEPARATOR) >= 0) {
            String[] parts = message.split(PATTERN_SEPARATOR);

            title.append(parts[0]);
            message = parts[1];
        }

        return message;
    }
}
